// 构建一个 /posts 路由，实现文章的创建、读取、更新和删除
// 操作，数据存储在数据库中。
const express = require("express");
const mysql = require("mysql");
const app = express();
const db = mysql.createPool({
  host: "127.0.0.1",
  user: "root",
  password: "root",
  database: "node",
});
app.get("/select", (req, res) => {
  db.query("select * from work", (err, result) => {
    if (err) {
      return res.send({ code: 0, msg: "查询失败", data: null });
    }
    res.send({ code: 999, msg: "查询成功", data: result });
  });
});
app.post("/create", (req, res) => {
  db.query(
    `insert into work(name,password) value("${req.body.name}","${req.body.password}")`,
    (err, result) => {
      if (err) return res.send({ code: 0, msg: err });
      if (result.affectedRows > 0) {
        return res.send({ code: 999, msg: "添加成功" });
      } else {
        return res.send({ code: 0, msg: "添加失败" });
      }
    }
  );
});
app.put("/update", (req, res) => {
  db.query(
    `update work set ? where id=${req.body.id}`,
    { name: b, password: a },
    (err, result) => {
      if (err) return res.send({ code: 0, msg: err });
      if (result.affectedRows > 0) {
        return res.send({ code: 999, msg: "修改成功" });
      } else {
        return res.send({ code: 0, msg: "修改失败" });
      }
    }
  );
});
app.delete("/clear", (req, res) => {
  db.query(`delete from work where id=${req.body.id}`, (err, result) => {
    if (err) return res.send({ code: 0, msg: err });
    if (result.affectedRows > 0) {
      return res.send({ code: 999, msg: "删除成功" });
    } else {
      return res.send({ code: 0, msg: "删除失败" });
    }
  });
});
app.listen(3000, () => {
  console.log("启动成功");
});
